import { WebGLRenderTarget, DepthTexture, DepthFormat, UnsignedShortType, ClampToEdgeWrapping, NearestMipmapNearestFilter, NearestFilter, WebGLRenderer, Camera } from "three";
import { App } from "../Engine";

/**
 * 深度缓存的辅助类
 */
export default class DepthTargetHelper {
    public renderTarget: WebGLRenderTarget;
    
    public initRenderTarget() {
        let targetSize = 1024;
        this.renderTarget = new WebGLRenderTarget(targetSize, targetSize, { depthBuffer: true });
        this.renderTarget.depthTexture = new DepthTexture(targetSize, targetSize);
        this.renderTarget.depthTexture.format = DepthFormat;
        this.renderTarget.depthTexture.type = UnsignedShortType;
        this.renderTarget.depthTexture.wrapS = ClampToEdgeWrapping;
        this.renderTarget.depthTexture.wrapT = ClampToEdgeWrapping;
        this.renderTarget.depthTexture.minFilter = NearestMipmapNearestFilter;
        this.renderTarget.depthTexture.magFilter = NearestFilter;
    }

    public preRenderTarget(virturalCamera: Camera) {
        let app = App.getInstance();
        let renderer: WebGLRenderer = app.three.renderer;

        if (this.renderTarget) {
            this.renderTarget.dispose();
            this.initRenderTarget();
        }
        renderer.setRenderTarget(this.renderTarget);
        app.three.scene.fog = null; //第一遍渲染，不需要用雾
        renderer.clearDepth();
        renderer.render(app.three.scene, virturalCamera.clone());
        app.three.scene.fog = app.background.fog; //第一遍渲染完成后，把雾添加回场景
        renderer.setRenderTarget(null);
    }

}